// @charset "utf-8";
/**
 * 融资融券view
 */
define(function (require, exports, module) {
	var hqQuote = require('./rzrqquote');
	var rzrqChart = require('./rzrqchart');

	var rzrqParam = {
		rzrqData : [],
		contrastData : [],
		shData : [],
		yminData : 8000,
		categories : [],
		xAxisTime : []
	};
	var rzrqView = {
		delay : 1000,
		count : 0,
		autoRzrq : null,
		isSuccess : false,
		makeDataArray : function (arr, str, isdate) {
			var arrayObj = [];
			$.each(arr, function(i, n) {
				if (isdate) {
					var theDate = n[str].substr(4, 2) + '-' + n[str].substr(6, 2);
					arrayObj.push(theDate);
				} else {
					arrayObj.push(Math.round(n[str] / 100000000));
				}

			});
			return arrayObj;
		},
		makeArray : function (arr, str) {
			var arrayObj = [];
			$.each(arr, function(i, n) {
				arrayObj.push(n[str]);
			});
			return arrayObj;
		},
		request : function () {
			var self = this;
			self.count++;
			var url = '/zx/freeclient/homepage/rzrq.json';

			var bool = commonMethod.thsQuote.requestZxData({
				url: url,
				onready: function(res) {
					self.isSuccess = true;
					if (res == '[]') {
						self.render('NUL');
					} else {
						self.render(res);
					}
				}
			});
			if (!bool || !self.isSuccess) {
				if (self.count > 5) {
					self.delay = 60000;
					self.render('NUL');
				}
				self.autoRzrq = setTimeout(function () {
					self.request();
				}, self.delay);
			} else {
				clearTimeout(self.autoRzrq);
			}
		},
		render : function (result) {
			var self = this;
			if (result != 'NUL') {
				var resultData = JSON.parse(result);
				var data = resultData.data;

				rzrqParam.rzrqData = self.makeDataArray(data, 'balance');
				rzrqParam.contrastData = self.makeDataArray(data, 'relative');
				rzrqParam.yminData = Math.min.apply(null, rzrqParam.rzrqData) - 500;
				rzrqParam.categories = self.makeDataArray(data, 'date', true);
				rzrqParam.xAxisTime = self.makeArray(data, 'date');

				hqQuote.request(self.renderChart, ['1A0001'], 16384, rzrqParam.xAxisTime);
			}
		},
		renderChart : function (data) {
			rzrqParam.shData = [];
			for (var k = 0; k < 10; k++) {
				rzrqParam.shData.push(parseFloat(data[rzrqParam.xAxisTime[k]]['close']['1A0001']));
			}
			// alert(JSON.stringify(rzrqParam));
			rzrqChart.render(rzrqParam);
		}
	};

	module.exports = rzrqView;
});